from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area


class AreasView(View):
    """
    获取省份信息
    前端  加载收货地址页面 会自动发送请求 获取省份信息

    后端
    请求  无参数
    逻辑； 查询所有省份
    响应   {code:0,erromsg:'ok' ,"province_list":[{"id":id,"name":xxx},{"id":id,"name":xxx},{"id":id,"name":xxx}]}

    路由   get  /areas/
    """

    def get(self, request):
        province_list = cache.get("provinces")
        if not province_list:
            # 1 查询所有省份
            try:
                provinces = Area.objects.filter(parent=None)
                # 2 转换为字典
                province_list = []
                for province in provinces:
                    province_list.append({"id": province.id, "name": province.name})
                cache.set("provinces", province_list, 3600 * 24)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "查询失败"})
        # 3 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "province_list": province_list})


class SubAreaView(View):
    """
    获取市区县信息
    前端： 用户选择省份或者市的时候  发送请求，获取下一级信息
    后端：
     请求   传递省份 或者市 的id
     逻辑： 根据id查area对象，获取下一级信息，转为字典数据
     返回响应  json
    路由  get /areas/<id>/
    response.data.sub_data.subs;
    {
      "code":"0",
      "errmsg":"OK",
      "sub_data":{
          "id":130000,
          "name":"河北省",
          "subs":[
              {
                  "id":130100,
                  "name":"石家庄市"
              },
              ......
          ]
      }
    }
    """

    def get(self, request, id):
        sub_data = cache.get("sub_areas%s" % id)
        if not sub_data:
            try:
                # 1 获取id
                # 2 根据id查询省或者市的对象
                parent_obj = Area.objects.get(id=id)
                # 3 获取省或市下一级的所有数据
                sub_objs = parent_obj.subs.all()
                # 4 转为字典
                subs = []
                for sub in sub_objs:
                    subs.append({"id": sub.id, "name": sub.name})
                sub_data = {"id": id, "name": parent_obj.name, "subs": subs}
                cache.set("sub_areas%s" % id, sub_data, 3600 * 24)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "查询失败"})
        # 5 返回数据
        return JsonResponse({"code": 0, "errmsg": "ok", "sub_data": sub_data})
